<?php

namespace app\common\service;

use Upyun\Config;
use Upyun\Upyun;


class Upyun
{
	/**
	 * 上传图片
	 * @Author   zhibin
	 * @DateTime 2020-01-05
	 * @param    [type]     $file D:\wwwroot\ttkan_cn\public\static\index\images\banner03.jpg
	 * @return   [type]           [description]
	 */
	public function upload($file, $new_file_name='')
	{
		// 用于签名的公钥和私钥
		$config = config('upyun');
		// 初始化签权对象
		$bucketConfig = new Config($config['BUCKET'], $config['AccessKey'], $config['SecretKey']);
		$client = new Upyun($bucketConfig);

		if (empty($new_file_name)) {
	        $ext = pathinfo($file, PATHINFO_EXTENSION);  //获取文件扩展名
	        $new_file_name = date('Y') .'/'. date('m') .'/'. date('d') .'/'. substr(md5($file), 0, 10) . time() .'.'. $ext; //构建上传路径名称
		}
		
        $fileObj = fopen($file, 'r'); //获取上传的临时文件
		$res = $client->write($new_file_name, $fileObj); ///up/dd.jpg 存储的文件名
		// 打印上传结果
		// pre($res);

		return $res ? $new_file_name : ''; //$files['key'] 文件路径
	}

	/**
	 * 生成可访问第路径
	 * @Author   zhibin
	 * @DateTime 2020-01-05
	 * @param    [type]     $dir [description]
	 * @return   [type]          [description]
	 */
	public static function getFile($dir)
	{
		$config = config('upyun');

		return $config['domain'].$dir;
	}
}